package com.sunny.netty.handler;

import com.sunny.netty.entity.OrderRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * 序列化客户端
 *
 * @author sunny
 * @date 2018/12/10
 */
public class OrderClient extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        channel.pipeline().addLast(new ObjectDecoder(1024 * 1024, ClassResolvers.weakCachingResolver(this.getClass().getClassLoader())))
                .addLast(new ObjectEncoder())
                .addLast(new OrderClientHandler());
    }

    private class OrderClientHandler extends ChannelHandlerAdapter {
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 0; i < 3; i++) {
                ctx.write(request(i));
            }
            ctx.flush();
        }

        private Object request(int i) {
            OrderRequest request = new OrderRequest();
            request.setAddress("上海市浦东新区小黑鱼");
            request.setOrderId(i);
            request.setPhoneNumber("185*****418");
            request.setUserName("Sunny");
            request.setProductName("一起学Netty");
            return request;
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("Receive Server Response:[" + msg + "]");
        }
    }

    public static void connect(String host, Integer port) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new OrderClient());

        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        connect("127.0.0.1", 4040);
    }

}
